package com.stlm2.dems.user.service;

import com.stlm2.core.redis.RedisClient;
import com.stlm2.dems.dao.UserDao;
import com.stlm2.dems.entity.User;
import com.stlm2.dems.user.dao.*;
import com.stlm2.dems.user.entity.*;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service("userRolePrivilegeService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class UserRolePrivilegeService extends BaseServiceImpl<UserRolePrivilege> {

	@Resource
	private UserRolePrivilegeDao userRolePrivilegeDao;
	@Resource
	private RoleDao roleDao;
	@Resource
	private UserDao userDao;
	@Resource
	private SystemPrivilegeDao systemPrivilegeDao;
	@Resource
	private UserRoleDao userRoleDao;

	@Override
	protected BaseDao <UserRolePrivilege> getDao() {
		return userRolePrivilegeDao;
	}

	/*
*查找角色拥有的资源树
* zlq
*@param  token
* @param  roleId ：角色ID
*
*/
	public String getByRolePrivilege(ModelMap map,String token,String roleId){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		if(!NumberUtils.isNumber(roleId)){
			return CodeContent.getModelByCode(0, "角色不能为空", map);
		}
		SystemPrivilege superMenu=new SystemPrivilege();
		superMenu.setPermissionType(PermissionType.SuperMenu);
		superMenu.setIsValid(IsValid.Normal);
		//获取主菜单资源列表
		List<SystemPrivilege> superMenuList=systemPrivilegeDao.queryPageView(-1,-1,superMenu).getRecords();
		//获取角色拥有的资源列表
		List<SystemPrivilege> rolePrivilegeList=systemPrivilegeDao.getByRoleId(Integer.parseInt(roleId));
		List<String> rolePermissionName=new ArrayList<String>();
		for(SystemPrivilege roleSystemPrivilege:rolePrivilegeList){
			rolePermissionName.add(roleSystemPrivilege.getPermissionName());
		}
		Role role=roleDao.getById(Integer.parseInt(roleId));
		if(role!=null){
			map.put("role",role.getName());
		}else {
			map.put("role","");
		}

		map.put("superMenuList",convertsuperMenuList2(superMenuList,rolePermissionName,new ArrayList<String>()));
		map.put("code",1);
		map.put("msg","success");
		return  new JSONObject(map).toString();
	}


/*
*给角色添加权限
* *zlq
* @param  token
* @param  roleId ：角色ID
* @param  permissionIds:多个资源权限ID拼接的字符串
 */
	public  String roleAddPermission(ModelMap map,String token,String roleId,String permissionIds){
		JedisPool pool = null;
		Jedis jedis = null;
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		if(!NumberUtils.isNumber(roleId)){
			return CodeContent.getModelByCode(0, "角色不能为空", map);
		}

		try {
			pool = RedisClient.getPool();
			jedis = pool.getResource();
		Role role=roleDao.getById(Integer.parseInt(roleId));
		if(role==null){
			return CodeContent.getModelByCode(0, "角色ID不正确", map);
		}
		UserRolePrivilege userRolePrivilege=new UserRolePrivilege();
		userRolePrivilege.setRoleId(role.getId());
		userRolePrivilege.setUserRolePrivilegeType(UserRolePrivilegeType.PrivilegeGiveRole);
		List<UserRolePrivilege> userRolePrivilegeList=userRolePrivilegeDao.queryPageView(-1,-1,userRolePrivilege).getRecords();
		if(userRolePrivilegeList.size()>0){
			//删除之前存在的权限
			for(UserRolePrivilege userRolePrivilege1:userRolePrivilegeList){
				userRolePrivilegeDao.delete(userRolePrivilege1.getId());
			}
		}

		if (!StringUtils.isEmpty(permissionIds)) {
			String[] permissionId = permissionIds.split(",");
			for(int i=0;i<permissionId.length;i++){
				//添加新的权限
				UserRolePrivilege userRolePrivilege2 =new UserRolePrivilege();
				userRolePrivilege2.setRoleId(role.getId());
				userRolePrivilege2.setSystemPrivilegeId(Integer.parseInt(permissionId[i]));
				userRolePrivilege2.setUserRolePrivilegeType(UserRolePrivilegeType.PrivilegeGiveRole);
				userRolePrivilegeDao.add(userRolePrivilege2);
			}
		}

		//查找拥有该角色的用户
		List<User> roleUserList=userDao.getByRoleId(role.getId());
		if(roleUserList.size()>0){
			for(User user : roleUserList){
				Set<String> userPrivilegeList=jedis.keys(user.getName() + "userPrivilege*");
				if(userPrivilegeList!=null&&userPrivilegeList.size()>0){
					for (String userPrivilege:userPrivilegeList) {//删除之前存入缓存的用户权限
						jedis.del(userPrivilege);
					}
				}
				Set<String> userRolesList=jedis.keys(user.getName() + "userRoles*");
				if(userRolesList!=null&&userRolesList.size()>0){
					for (String userRoles:userRolesList) {//删除之前存入用户角色
						jedis.del(userRoles);
					}
				}
			}
		}

		}catch (Exception e){
			e.printStackTrace();
			throw new RuntimeException();
		}
		finally {
			pool.returnResource(jedis);
		}


		return CodeContent.getModelByCode(1, "", map);
	}

	/*
*给用户添加权限
* *zlq
* @param  token
* @param  userId ：用户ID
* @param  permissionIds:多个权限ID拼接的字符串
 */
	public  String userAddPermission(ModelMap map,String token,String userId,String permissionIds){
		JedisPool pool = null;
		Jedis jedis = null;
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", map);
		}
		if(!NumberUtils.isNumber(userId)){
			return CodeContent.getModelByCode(0, "用户ID不能为空", map);
		}

		User user=userDao.getById(Integer.parseInt(userId));
		if(user==null){
			return CodeContent.getModelByCode(0, "用户ID不正确", map);
		}
		//查找用户的角色权限
		List <String> rolePrivilegeIds= new ArrayList<String>();
		UserRole userRole=userRoleDao.getByUserId(user.getId());
		if(userRole==null){
			return CodeContent.getModelByCode(0, "请先给用户赋予角色", map);
		}
		try {
			pool = RedisClient.getPool();
			jedis = pool.getResource();
		UserRolePrivilege rolePrivilege=new UserRolePrivilege();
		rolePrivilege.setRoleId(userRole.getRoleId());
		rolePrivilege.setUserRolePrivilegeType(UserRolePrivilegeType.PrivilegeGiveRole);
		List<UserRolePrivilege> rolePrivilegeList=userRolePrivilegeDao.queryPageView(-1,-1,rolePrivilege).getRecords();
		for(UserRolePrivilege userRolePrivilege:rolePrivilegeList){
			rolePrivilegeIds.add(String.valueOf(userRolePrivilege.getSystemPrivilegeId()));
		}
		//查找修改前的资源权限，然后删除
		UserRolePrivilege userRolePrivilege=new UserRolePrivilege();
		userRolePrivilege.setUserId(user.getId());
		userRolePrivilege.setUserRolePrivilegeType(UserRolePrivilegeType.PrivilegeGiveUser);
		List<UserRolePrivilege> userRolePrivilegeList=userRolePrivilegeDao.queryPageView(-1,-1,userRolePrivilege).getRecords();
		if(userRolePrivilegeList.size()>0){
			for(UserRolePrivilege userRolePrivilege1:userRolePrivilegeList){
				userRolePrivilegeDao.delete(userRolePrivilege1.getId());
			}
		}
		if (!StringUtils.isEmpty(permissionIds)) {
			String[] permissionId = permissionIds.split(",");
			//将新的资源权限进行添加
			for(int i=0;i<permissionId.length;i++){
				//判断新的权限ID中是否包含角色中已经存在的资源权限ID，避免重复权限
				if(!rolePrivilegeIds.contains(permissionId[i].trim())){
					UserRolePrivilege userRolePrivilege2 =new UserRolePrivilege();
					userRolePrivilege2.setUserId(user.getId());
					userRolePrivilege2.setSystemPrivilegeId(Integer.parseInt(permissionId[i].trim()));
					userRolePrivilege2.setUserRolePrivilegeType(UserRolePrivilegeType.PrivilegeGiveUser);
					userRolePrivilegeDao.add(userRolePrivilege2);
				}
			}
		}

			Set<String> userPrivilegeList=jedis.keys(user.getName() + "userPrivilege*");
			if(userPrivilegeList!=null&&userPrivilegeList.size()>0){
				for (String userPrivilege:userPrivilegeList) {//删除之前存入缓存的用户权限
					jedis.del(userPrivilege);
				}
			}
			Set<String> userRolesList=jedis.keys(user.getName() + "userRoles*");
			if(userRolesList!=null&&userRolesList.size()>0){
				for (String userRoles:userRolesList) {//删除之前存入用户角色
					jedis.del(userRoles);
				}
			}
		}catch (Exception e){
			e.printStackTrace();
			throw new RuntimeException();
		}
		finally {
			pool.returnResource(jedis);
		}
		return CodeContent.getModelByCode(1, "", map);
	}


/*
*查找用户资源列表树
* zlq
*@param  token
* @param  userId ：用户ID
*
*/
public String getByUserPrivilege(ModelMap map,String token,String userId){
	List<String> rolePermissionName=new ArrayList<String>();
	List<String> userPermissionName=new ArrayList<String>();
	if (StringUtils.isEmpty(token)) {
		return CodeContent.getModelByCode(-1, "", map);
	}
	User loginUser = userDao.getByToken(token);
	if (loginUser == null) {
		return CodeContent.getModelByCode(-1, "", map);
	}
	if(!NumberUtils.isNumber(userId)){
		return CodeContent.getModelByCode(0, "用户ID不能为空", map);
	}
	User user=userDao.getById(Integer.parseInt(userId));
	if(user==null){
		return CodeContent.getModelByCode(0, "用户ID不存在", map);
	}
	SystemPrivilege superMenu=new SystemPrivilege();
	superMenu.setPermissionType(PermissionType.SuperMenu);
	superMenu.setIsValid(IsValid.Normal);
	//获取主菜单资源列表
	List<SystemPrivilege> superMenuList=systemPrivilegeDao.queryPageView(-1,-1,superMenu).getRecords();
	UserRole userRole=userRoleDao.getByUserId(user.getId());
	//获取用户角色拥有的资源列表
	List<SystemPrivilege> rolePrivilegeList=systemPrivilegeDao.getByRoleId(userRole.getRoleId());
	for(SystemPrivilege roleSystemPrivilege:rolePrivilegeList){
		rolePermissionName.add(roleSystemPrivilege.getPermissionName());
	}
	//获取用户额外拥有的资源列表
	List<SystemPrivilege> userPrivilegeList=systemPrivilegeDao.getByUserId(user.getId());
	for(SystemPrivilege userSystemPrivilege:userPrivilegeList){
		userPermissionName.add(userSystemPrivilege.getPermissionName());
	}
	map.put("userAccount",user.getName());
	map.put("userName",user.getRealName());
	map.put("superMenuList",convertsuperMenuList2(superMenuList,rolePermissionName,userPermissionName));
	map.put("code",1);
	map.put("msg","success");
	return  new JSONObject(map).toString();
}


	public List<ModelMap> convertsuperMenuList2(List<SystemPrivilege> systemPrivilegeList,List<String> rolePermissionName,List<String> userPermissionName) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (systemPrivilegeList != null && systemPrivilegeList.size() > 0) {
			for (SystemPrivilege systemPrivilege : systemPrivilegeList) {
				ModelMap map = buildModelsuperMenu2(systemPrivilege,rolePermissionName,userPermissionName);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelsuperMenu2(SystemPrivilege systemPrivilege,List<String> rolePermissionName,List<String> userPermissionName) {
		ModelMap model = new ModelMap();
		model.put("superId",systemPrivilege.getId());
		model.put("superCnName",systemPrivilege.getCnName());
		if(rolePermissionName.contains(systemPrivilege.getPermissionName())){
			model.put("isRoleValid",true);
		}else {
			model.put("isRoleValid",false);
		}
		if(userPermissionName.contains(systemPrivilege.getPermissionName())){
			model.put("isUserValid",true);
		}else {
			model.put("isUserValid",false);
		}
		//获取子菜单资源列表
		SystemPrivilege menu=new SystemPrivilege();
		menu.setSuperId(systemPrivilege.getId());
		menu.setIsValid(IsValid.Normal);
		List<SystemPrivilege> menuList=systemPrivilegeDao.queryPageView(-1,-1,menu).getRecords();
		model.put("menuList",convertMenuList2(menuList,rolePermissionName,userPermissionName));
		return  model;
	}
	public List<ModelMap> convertMenuList2(List<SystemPrivilege> systemPrivilegeList,List<String> rolePermissionName,List<String> userPermissionName) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (systemPrivilegeList != null && systemPrivilegeList.size() > 0) {
			for (SystemPrivilege systemPrivilege : systemPrivilegeList) {
				ModelMap map = buildModelMenu2(systemPrivilege,rolePermissionName,userPermissionName);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelMenu2(SystemPrivilege systemPrivilege,List<String> rolePermissionName,List<String> userPermissionName) {
		ModelMap model = new ModelMap();
		model.put("MenuId",systemPrivilege.getId());
		model.put("MenuCnName",systemPrivilege.getCnName());
		if(rolePermissionName.contains(systemPrivilege.getPermissionName())){
			model.put("isRoleValid",true);
		}else {
			model.put("isRoleValid",false);
		}
		if(userPermissionName.contains(systemPrivilege.getPermissionName())){
			model.put("isUserValid",true);
		}else {
			model.put("isUserValid",false);
		}
		//获取子菜单下的按钮资源列表
		SystemPrivilege button=new SystemPrivilege();
		button.setSuperId(systemPrivilege.getId());
		button.setIsValid(IsValid.Normal);
		List<SystemPrivilege> buttonList=systemPrivilegeDao.queryPageView(-1,-1,button).getRecords();
		model.put("buttonList",convertButtonList2(buttonList,rolePermissionName,userPermissionName));
		return  model;
	}
	public List<ModelMap> convertButtonList2(List<SystemPrivilege> systemPrivilegeList,List<String> rolePermissionName,List<String> userPermissionName) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (systemPrivilegeList != null && systemPrivilegeList.size() > 0) {
			for (SystemPrivilege systemPrivilege : systemPrivilegeList) {
				ModelMap map = buildModelButton2(systemPrivilege,rolePermissionName,userPermissionName);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelButton2(SystemPrivilege systemPrivilege,List<String> rolePermissionName,List<String> userPermissionName) {
		ModelMap model = new ModelMap();
		model.put("buttonId",systemPrivilege.getId());
		model.put("buttonCnName",systemPrivilege.getCnName());
		if(rolePermissionName.contains(systemPrivilege.getPermissionName())){
			model.put("isRoleValid",true);
		}else {
			model.put("isRoleValid",false);
		}
		if(userPermissionName.contains(systemPrivilege.getPermissionName())){
			model.put("isUserValid",true);
		}else {
			model.put("isUserValid",false);
		}
		return  model;
	}



}